package com.sunducation.wts.livedata

import android.os.SystemClock
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import java.util.*

class LiveDataTimerViewModel : ViewModel(){
    override fun onCleared() {
        super.onCleared()
    }

    private val ONE_SECOND = 1000L;

    private val mElapsedTime : MutableLiveData<Long> = MutableLiveData();

    private var mInitialTime: Long = 0;

    /**
     * 在初始化时启动一个定时任务，每隔一秒通过postValue方法刷新一下数据。
     */
    fun LiveDataTimerViewModel() {
        if(mInitialTime != 0L) {
            return
        }
        mInitialTime = SystemClock.elapsedRealtime();

         val timer:Timer = Timer();

        timer.scheduleAtFixedRate(object :TimerTask() {
            override fun run() {
                var newValue: Long = (SystemClock.elapsedRealtime() - mInitialTime) / 1000;
                mElapsedTime.postValue(newValue); //子线程使用这个
                //mElapsedTime.value = newValue;  //主线程中使用这个
            }
        },ONE_SECOND,ONE_SECOND);

    }

    fun  getElapsedTime():MutableLiveData<Long> {
        return mElapsedTime;
    }
}